<template>
  <ContainerBox type="common" class="question-edit">
    <h3>问题标题：</h3>
    <input placeholder="请输入问题的标题" v-model="title"/>
    <textarea placeholder="请输入问题的内容" v-model="content"/>
    <div class="shots">
      <div class="pic-container" v-for="(item,index) in shots" v-if="item.show">
        <img :src="item.pic" >
        <i class="el-icon-circle-close" @click="deletePic(index)"></i>
      </div>
      <div class="upload" v-if="shots[0] !== 0">
        <input id="shot" type="file" ref="shot" @change="uploadShot" hidden>
        <label for="shot">
          <div>上传截图</div>
        </label>
      </div>
    </div>
    <div class="options">
      <div class="save-btn" v-if="type==='update'" @click="updateQuestion()">保存</div>
      <div class="post-btn" v-if="type==='post'" @click="postQuestion()">发布</div>
      <div class="cancel-btn" @click="backList">返回</div>
    </div>
  </ContainerBox>
</template>

<script>
import ContainerBox from '../../../box/container_box'
export default {
  name: "skill_page_questions_edit",
  components :{ContainerBox},
  data() {
    return {
      type: '',
      title: '',
      content: '',
      pictureList: [],
      shots: [
        1, // 代表接下来的空位，0代表无空位上传截图
        {
          pic: '',
          file: '',
          show: false,
        },{
          pic: '',
          file: '',
          show: false,
        },{
          pic: '',
          file: '',
          show: false,
        }
      ],
      ossPic: []
    }
  },
  mounted() {
    this.getEditType();
    switch (this.type) {
      case "post" : this.newQuestionDetail();break;
      case "update": this.getQuestionDetail();break;
    }
  },
  methods: {
    backList() {
      this.$router.push('/skillPage/'+this.$route.params.id+'/questions/list');
    },
    getEditType() {
      if(this.$route.params.questionId === '0') {
        this.type = 'post';
      } else {
        this.type = 'update';
      }
    },
    getQuestionDetail() {
      const self = this;
      const questionId = this.$route.params.questionId;
      this.$axios({
        method: 'get',
        url: '/skill/question/get/' + questionId
      }).then(function (response) {
        var jsonString = JSON.stringify(response.data);
        var jsonObj = JSON.parse(jsonString);
        console.log("jsonObj", jsonObj);
        if (jsonObj.success){
          self.title = jsonObj.data.VO.title;
          self.content = jsonObj.data.VO.content;
          for (let i=0; i<jsonObj.data.VO.pictureList.length; i++) {
            self.$set(self.shots[i+1],'pic',jsonObj.data.VO.pictureList[i]);
            self.$set(self.shots[i+1],'show',true);
          }
          self.$set(self.shots,0,(jsonObj.data.VO.pictureList.length+1)%4);
          console.log(self.shots);
        } else {
          // 异常跳转
        }

      })

    },
    newQuestionDetail() {

    },


    // 返回之前的页面
    backHistory: function () {
      this.$router.back();
    },

    // 获得下一个图片位置
    getNextBlank() {
      // 上传后，获取接下来的空位
      let i =1;
      for (i; i<this.shots.length; i++) {
        if (!this.shots[i].show) {
          this.shots[0] = i;
          break;
        }
      }
      if (i === this.shots.length) {
        this.shots[0] = 0;
      }

    },



    // 更新提问
    async updateQuestion() {
      const self = this;
      // 上传oss，得到云地址
      await this.getAllOssPicture();
      // 获取所有图片地址，但是还是本地地址，不是云地址
      let picList = self.shots.filter(item => { return item.show; }).map(item => { return item.pic});
      console.log(picList);
      this.$axios({
        method: 'put',
        url: '/skill/question/update',
        data: {
          title: self.title,
          content: self.content,
          id: self.$route.params.questionId,
          pictureList: picList
        }
      }).then(function (response) {
        var jsonString = JSON.stringify(response.data);
        var jsonObj = JSON.parse(jsonString);
        if (jsonObj.success) {
          self.$message({
            type: 'success',
            message: '问题修改成功!'
          });
          self.$router.back();
        } else {
          self.$message({
            type: 'warning',
            message: '问题修改失败!'
          });
        }
      })
    },

    // 发布提问
    async postQuestion() {
      const self = this;
      // 获取所有图片云地址
      await this.getAllOssPicture();

      // 获取所有图片云地址
      let picList = self.shots.filter(item => { return item.show; }).map(item => { return item.pic});

      console.log(picList);
      this.$axios({
        method: 'post',
        url: '/skill/question/save',
        data: {
          title: self.title,
          skillId: self.$route.params.id,
          sectionId: self.$route.query.sectionId?self.$route.query.sectionId:null,
          pictureList: picList,
          content:"问题内容"
        }
      }).then(function (response) {
        var jsonString = JSON.stringify(response.data);
        var jsonObj = JSON.parse(jsonString);
        if (jsonObj.success) {
          self.$message({
            type: 'success',
            message: '问题发布成功!'
          });
          self.backHistory();
        } else {
          self.$message({
            type: 'warning',
            message: '问题发布失败!'
          });
        }
      })
    },


    // 上传本地图片
    uploadShot() {
      const file = this.$refs.shot.files[0];
      let url = null ;
      if (window.createObjectURL!=undefined) { // basic
        url = window.createObjectURL(file) ;
      }else if (window.webkitURL!=undefined) { // webkit or chrome
        url = window.webkitURL.createObjectURL(file) ;
      }else if (window.URL!=undefined) { // mozilla(firefox)
        url = window.URL.createObjectURL(file);
      }
      console.log(url);
      let blank = this.shots[0];
      this.shots[blank].file = file;
      this.shots[blank].pic = url;
      this.shots[blank].show = true;

      this.getNextBlank();
    },

    // 上传所有图片文件到oss，获取所有云地址
    async getAllOssPicture() {
      for (let i=1; i<this.shots.length; i++) {
        if (this.shots[i].show && this.shots[i].file !== '') {
          await this.getOssPicture(this.shots[i].file, i); // 此方法内部获取云地址成功，但是之后shot[].pic并没有真正赋值
        }
      }
    },

    // 上传单个图片文件到oss，成功获取云地址
    async getOssPicture(file, i) {
      const self = this;
        let picUrl = "";
        // 上传部分
        let data = new FormData();
        data.append('file', file);
        let res = await this.$axios({
          url:'/oss',
          method: 'post',
          data,
          headers: {},
          //原生获取上传进度的事件
          onUploadProgress: function(progressEvent) {
            let complete = (progressEvent.loaded / progressEvent.total * 100 | 0) + '%'
            console.log('上传 ' + complete)
          }
        })
        var jsonString = JSON.stringify(res.data);
        var jsonObj = JSON.parse(jsonString);
        picUrl = jsonObj.data.url;
        // self.shots[i].pic = picUrl;
        // 云图片地址picUrl成功获取，赋值给self.shots[i].pic，但是后面还是会失效
        self.$set(self.shots[i], 'pic',picUrl);
    },

    // 点击删去图片
    deletePic(index) {
      console.log(index);
      this.shots[index].file = '';
      this.shots[index].pic = '';
      this.shots[index].show = false;
      this.getNextBlank();
    }
  }
}
</script>

<style lang="scss" scoped>
@import "../../../.././assets/style/common";
.question-edit {
  position: relative;
  display: flex;
  flex-direction: column;
  input {
    @include input_1();
    margin-bottom: 20px;
  }
  textarea {
    @include input_1();
    width: 750px;
    height: 250px;
  }
  .shots {
    margin-top: 20px;
    margin-left: 20px;
    display: flex;
    height: 200px;
    .upload {
      cursor: pointer;
      margin-left: 20px;
      @include btn-add();
    }
    .pic-container {
      position: relative;
      margin-right: 25px;
      img {
        width: 180px;
        height: 180px;
        border-radius: 5%;
      }
      .el-icon-circle-close{
        cursor: pointer;
        position: absolute;
        right: -18px;
        top: 0;
      }
    }
  }
  .options {
    right: 135px;
    top: 70px;
    position: absolute;
    display: flex;
    width: 160px;
    justify-content: space-between;
    align-items: center;
    //margin-left: 100px;
    .save-btn {
      width: 60px;
      @include btn_add();
    }
    .post-btn {
      width: 60px;
      @include btn-add();
    }
    .cancel-btn {
      width: 60px;
      @include btn-delete();
    }
  }
}
</style>
